/*
 * (C) Copyright 2013 George Daswani (georgedaswani@gmail.com) and others.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl-2.1.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *    George Daswani (georgedaswani@gmail.com)
 */

package am.api.model;

import java.io.Serializable;
import java.util.Date;

import org.apache.commons.lang.builder.EqualsBuilder;
import org.apache.commons.lang.builder.HashCodeBuilder;
import org.apache.commons.lang.builder.ToStringBuilder;

public class AMDate implements Serializable {

	public final static long serialVersionUID = 1L;

	public final static AMDate create(Date date) {

		if (date == null) {
			throw new IllegalArgumentException("invalid date argument");
		}

		// java dates in time value are UTC / GMT already but
		// milliseconds, not seconds

		long value = date.getTime() / 1000l;

		if (((long) Integer.MAX_VALUE) < value) {
			throw new IllegalStateException();
		}

		return new AMDate((int) value);

	}

	public final static AMDate fromUNIXInt(int unixUTC) {
		return new AMDate(unixUTC);
	}

	public final static Date toDate(int unixUTC) {
		return new Date((long) unixUTC * 1000l);
	}

	private final int value;

	private AMDate(int value) {
		this.value = value;
	}

	public boolean equals(Object obj) {
		if (obj == null) {
			return false;
		}
		if (obj == this) {
			return true;
		}
		if (obj.getClass() != getClass()) {
			return false;
		}
		AMDate rhs = (AMDate) obj;
		return new EqualsBuilder().appendSuper(super.equals(obj))
				.append(value, rhs.value).isEquals();
	}

	public int getValue() {
		return value;
	}

	public int hashCode() {
		return new HashCodeBuilder(57, 1).append(value).toHashCode();
	}

	public final Date toDate() {
		return new Date((long) value * 1000l);
	}

	public String toString() {
		return new ToStringBuilder(this).append("value", value).toString();
	}
}
